﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web;
using System.Linq;
using Ue.Extensions;

namespace Ue.Components.PropertyMappings
{
    public static class PropertyMappingHelper
    {
        public static void MappingProperties(object mappingObject, HttpContext context)
        {
            var metadata = GetMetadata(mappingObject.GetType());
            foreach (var property in metadata.Keys)
            {
                object value = GetValue(metadata[property], context);
                if (value != null)
                {
                    property.SetValue(mappingObject, Convert.ChangeType(value, property.PropertyType), null);
                }
            }
        }

        private static IDictionary<Type, IDictionary<PropertyInfo, IList<PropertyMappingAttribute>>> metadataCache = new Dictionary<Type, IDictionary<PropertyInfo, IList<PropertyMappingAttribute>>>();
        public static IDictionary<PropertyInfo, IList<PropertyMappingAttribute>> GetMetadata(Type type)
        {
            if (!metadataCache.ContainsKey(type))
            {
                metadataCache[type] = type.GetProperties<PropertyMappingAttribute>();
            }

            return metadataCache[type];
        }

        private static object GetValue(IEnumerable<PropertyMappingAttribute> metadata, HttpContext context)
        {
            foreach (var att in metadata)
            {
                var result= context.Request.GetQueryValue<object>(att.Key, att.Source);

                if (result != null) return result;
            }

            return null;
        }
    }
}
